<template>
	<view class="list-scroll-container">
		<scroll-view scroll-y="true" class="list-scroll" @refresherrefresh="refresherrefresh">
			<view>
				<view class="" v-for="i, index in list" :key="index">
					<MainItemCard :data="i" @changeAlarm="changeAlarm" @refresh="fetchData()"></MainItemCard>
				</view>
			</view>
			<view class="addBtn" @click="addMedicine">
				新增药品
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import {
	ref,
	defineProps,
	watch,
	onBeforeMount
} from 'vue';

import { useUserStore } from '../../store/User';

const props = defineProps({
	index: {
		type: Number,
		default: () => (0)
	}
});
const userStore = useUserStore();

const isLoading = ref(false);
const list = ref([]);
const alarmDayList = ref([0, 1, 2, 3, 4, 5, 6]);

// 获取familyid以及相关分类id
const { familyId } = uni.getStorageSync('userInfo');

const cate = uni.getStorageSync('cate');

const fetchData = () => {
	isLoading.value = true;
	// 调用云函数获取药品列表
	uniCloud.callFunction({
		name: 'getMedicine',
		data: {
			familyId: familyId,
			categoryId: cate[props.index].categoryId
		},
		success: res => {
			uni.showLoading({ title: '加载中' });
			list.value = res.result.data;
		},
		fail: err => {
			console.log(err);
		},
		complete: () => {
			uni.hideLoading();
		}

	});
};
onBeforeMount(() => {
	fetchData();
});
const refresherrefresh = () => {
	fetchData();
};

// 当index改变则重新获取数据
watch(() => props.index, async () => {
	// 修改state中的index
	userStore.changeIndex(props.index);
	// 重新获取数据
	await fetchData();
}, {
	immediate: true, // 立即执行	
});

const addMedicine = () => {
	// 跳转到新增药品页面
	uni.navigateTo({ url: '/pages/addMedicine/addMedicine' });
};

const changeAlarm = (medicine) => {
	// if (medicine.alarmFlag) {
	// 	// 取消闹钟
	// 	medicine.alarmFlag = false;
	// 	uni.showToast({
	// 		title: '已关闭提醒',
	// 		icon: 'success'
	// 	});
	// } else {
	// 设置闹钟
	if (!medicine.reminderTime) {
		uni.showToast({
			title: '未设置提醒时间',
			icon: 'error'
		});
		return;
	}

	const { hour, minute } = medicine.reminderTime;
	setAlarm(hour, minute, medicine.name + '服药提醒');
	medicine.alarmFlag = true;
	// }

	// 更新数据库中的闹钟状态
	// uniCloud.callFunction({
	// 	name: 'updateMedicine',
	// 	data: {
	// 		_id: medicine._id,
	// 		alarmFlag: medicine.alarmFlag
	// 	}
	// });
};

// 设置闹钟
const setAlarm = (hour, minutes, message) => {
	// #ifdef APP-PLUS
	if (plus.os.name.toLowerCase() === 'android') {
		try {
			const main = plus.android.runtimeMainActivity();
			const Intent = plus.android.importClass('android.content.Intent');
			const ComponentName = plus.android.importClass('android.content.ComponentName');

			// 尝试直接打开时钟应用的闹钟设置界面
			try {
				// 小米手机
				const miIntent = new Intent();
				miIntent.setComponent(new ComponentName('com.android.deskclock', 'com.android.deskclock.AlarmClock'));
				miIntent.setAction('android.intent.action.MAIN');
				miIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				main.startActivity(miIntent);

				uni.showToast({
					title: '请设置闹钟',
					icon: 'success',
					duration: 2000
				});
				return;
			} catch (miError) {
				console.log('非小米系统或打开失败，尝试其他方式');
			}

			try {
				// 华为手机
				const huaweiIntent = new Intent();
				huaweiIntent.setComponent(new ComponentName('com.android.deskclock', 'com.android.deskclock.DeskClock'));
				huaweiIntent.setAction('android.intent.action.MAIN');
				huaweiIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				main.startActivity(huaweiIntent);

				uni.showToast({
					title: '请设置闹钟',
					icon: 'success',
					duration: 2000
				});
				return;
			} catch (huaweiError) {
				console.log('非华为系统或打开失败，尝试其他方式');
			}

			// 如果特定品牌的尝试都失败，使用通用方式
			const intent = new Intent();
			intent.setAction('android.intent.action.MAIN');
			intent.addCategory('android.intent.category.LAUNCHER');
			intent.setPackage('com.android.deskclock');
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

			try {
				main.startActivity(intent);
				uni.showToast({
					title: '请设置闹钟',
					icon: 'success',
					duration: 2000
				});
			} catch (finalError) {
				// 如果所有方式都失败，显示错误信息
				console.error('无法打开时钟应用:', finalError);
				uni.showToast({
					title: '无法打开闹钟',
					icon: 'error'
				});
			}

		} catch (e) {
			console.error('设置闹钟失败:', e);
			uni.showToast({
				title: '无法设置闹钟',
				icon: 'error'
			});
		}
	} else {
		uni.showToast({
			title: '仅支持安卓系统',
			icon: 'none'
		});
	}
	// #endif

	// #ifndef APP-PLUS
	uni.showToast({
		title: '仅支持APP环境',
		icon: 'none'
	});
	// #endif
};
</script>


<style scoped lang="scss">
@import "../../uni.scss";

.list-scroll-container {
	height: 100%;
	// background-color: $base-color1;

	.list-scroll {
		overflow: hidden;
		height: 100%;
		box-sizing: border-box;
	}

	.addBtn {
		width: 300rpx;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		border-radius: 50rpx;
		margin: 20rpx auto;
		color: #fff;
		background-color: $btn-primary-color;
	}
}
</style>